
package com.mflex.WHSmartWhouseAd.activity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;

import com.mflex.WHSmartWhouseAd.R;
import com.mflex.WHSmartWhouseAd.adapter.MaterialOutStockTaskDetailAdapter;
import com.mflex.WHSmartWhouseAd.adapter.SMTMaterialOutStockTaskDetailAdapter;
import com.mflex.WHSmartWhouseAd.model.DoScanDataModel;
import com.mflex.WHSmartWhouseAd.model.DoTransTaskInfo;
import com.mflex.WHSmartWhouseAd.model.MaterialDetailForSMTModel;
import com.mflex.WHSmartWhouseAd.model.MaterialDetailModel;
import com.mflex.WHSmartWhouseAd.model.MaterialTaskSubmitModel;
import com.mflex.WHSmartWhouseAd.model.RequestModel;
import com.mflex.WHSmartWhouseAd.model.ScanDataForSMTModel;
import com.mflex.WHSmartWhouseAd.model.ScanVehPlateModel;
import com.mflex.WHSmartWhouseAd.model.TaskFlexOrder;
import com.mflex.WHSmartWhouseAd.model.TransTaskInfo;
import com.mflex.WHSmartWhouseAd.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xhttp2.reflect.TypeToken;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SMTMaterialOutStockTaskDetailActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    EditText txtTaskNo;
    EditText txtJDEPN;
    EditText txtFloor;
    EditText txtMaterialType;
    EditText txtUnremovedQty;
    EditText txtRemovedQty;
    EditText txtCarNo;
    EditText txtVehicleNo;
    EditText txtPanelNo;

    Spinner stvScanType;

    ListView txtList;

    Button buttonClear;
    Button buttonSubmit;
    MiniLoadingDialog mMiniLoadingDialog;

    String userName;
    String OPT;
    String TaskDetailID;
    private double scanQty = 0;
    List<MaterialDetailForSMTModel> MaterialDetails;
    ScanVehPlateModel ScanVehPlate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_smtmaterial_outstock_task_detail);
        mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this, "加载...");

        txtList = findViewById(R.id.lvList);

        txtTaskNo = findViewById(R.id.stvTaskNO);
        txtJDEPN = findViewById(R.id.stvJDEPN);
        txtFloor = findViewById(R.id.stvFloor);
        txtMaterialType = findViewById(R.id.stvMaterialType);
        txtUnremovedQty = findViewById(R.id.stvUnremovedQty);
        txtRemovedQty = findViewById(R.id.stvRemovedQty);
        txtCarNo = findViewById(R.id.stvCarNo);
        txtVehicleNo = findViewById(R.id.stvVehicleNo);
        txtPanelNo = findViewById(R.id.stvPanelNo);

        buttonClear = findViewById(R.id.button_clear);
        buttonSubmit = findViewById(R.id.button_save);


        Intent intent = getIntent();
        userName = intent.getStringExtra("userName");
        OPT = intent.getStringExtra("OPT");

        txtTaskNo.setText(intent.getStringExtra("TaskNo"));
        txtJDEPN.setText(intent.getStringExtra("JDEPN"));
        txtFloor.setText(intent.getStringExtra("Floor"));
        txtMaterialType.setText(intent.getStringExtra("MaterialClass"));
        txtUnremovedQty.setText(intent.getStringExtra("UnmovedQty"));
        txtRemovedQty.setText(intent.getStringExtra("movedQty"));
        TaskDetailID = intent.getStringExtra("TaskDetailID");

        Type listType = new TypeToken<List<MaterialDetailForSMTModel>>() {
        }.getType();
        MaterialDetails = (List<MaterialDetailForSMTModel>) JsonUtil.fromJson(intent.getStringExtra("list"), listType);
        SMTMaterialOutStockTaskDetailAdapter MaterialOutStockTaskDetailsAdapter = new SMTMaterialOutStockTaskDetailAdapter(SMTMaterialOutStockTaskDetailActivity.this, MaterialDetails);
        txtList.setAdapter(MaterialOutStockTaskDetailsAdapter);

        Collections.sort(MaterialDetails, (l1, l2) -> l1.getVehicleNumber().compareTo(l2.getVehicleNumber()));

//        Collections.sort(MaterialDetails, new Comparator<MaterialDetailForSMTModel>() {
//            @Override
//            public int compare(MaterialDetailForSMTModel t0, MaterialDetailForSMTModel t1) {
//                if () {
//                    return -1;
//                }
//                return 0;
//
//            }
//        });
//        Collections.sort(MaterialDetails, (s1, s2) -> Integer.compare(s1.getVehicleNumber().toString(), s2.getVehicleNumber().toString()));

        txtCarNo.setText("");
        txtCarNo.requestFocus();

        buttonClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SMTMaterialOutStockTaskDetailActivity.this, SMTMaterialOutStockTaskActivity.class);
                intent.putExtra("TaskNo", txtTaskNo.getText().toString());
                startActivity(intent);


            }
        });

        buttonSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                boolean flag = false;
//                for (TransTaskInfo details : list) {
//                    if (details.isCheckbox()) {
//                        TaskIds.add(details.getId());
//                        flag=true;
//                    }
//                }
//                if (!flag) {
//                    MediaPlayer mp = MediaPlayer.create(SMTMaterialOutStockTaskDetailActivity.this, R.raw.error_voice);mp.start();
//                    new MaterialDialog.Builder(SMTMaterialOutStockTaskDetailActivity.this)
//                            .iconRes(R.drawable.icon_warning)
//                            .title(R.string.tip_warning)
//                            .content("请选择要提交的任务单号")
//                            .positiveText(R.string.lab_submit)
//                            .show();
//
//                    return;
//                }
                mMiniLoadingDialog.show();
                MaterialTaskSubmitModel model = new MaterialTaskSubmitModel(txtTaskNo.getText().toString(), TaskDetailID, OPT);
                RequestModel requestModel = new RequestModel();
                requestModel.setJson(JsonUtil.toJson(model));
                String json = JsonUtil.toJson(requestModel);
                System.out.println(json);
                XHttp.post("api/WHSmartWhousePDA/SmartTaskDetailSubmitForSMT")
                        .upJson(JsonUtil.toJson(requestModel))
                        .syncRequest(false)
                        .onMainThread(true)
                        .execute(new SimpleCallBack<Boolean>() {
                            @Override
                            public void onSuccess(Boolean response) {
                                mMiniLoadingDialog.dismiss();
                                XToastUtils.success("提交成功", 3000);
//                                Intent intent=new Intent(SMTMaterialOutStockTaskDetailActivity.this,SMTMaterialOutStockTaskActivity.class);
//                                intent.putExtra("TaskNo", txtTaskNo.getText().toString());
//                                startActivity(intent);
                            }

                            @Override
                            public void onError(ApiException e) {
                                mMiniLoadingDialog.dismiss();
                                MediaPlayer mp = MediaPlayer.create(SMTMaterialOutStockTaskDetailActivity.this, R.raw.error_voice);
                                mp.start();
                                new MaterialDialog.Builder(SMTMaterialOutStockTaskDetailActivity.this)
                                        .iconRes(R.drawable.icon_warning)
                                        .title(R.string.tip_warning)
                                        .content(e.getMessage())
                                        .positiveText(R.string.lab_submit)
                                        .show();
                            }
                        });
            }
        });

        txtPanelNo.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent event) {
//                mMiniLoadingDialog.show();
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    if (StringUtils.equals("", txtPanelNo.getText().toString())) {
                        mMiniLoadingDialog.dismiss();
                        MediaPlayer mp = MediaPlayer.create(SMTMaterialOutStockTaskDetailActivity.this, R.raw.error_voice);
                        mp.start();
                        XToastUtils.success("请先扫描载盘号", 1500);
                        txtPanelNo.requestFocus();
                        return false;
                    }

//                    mMiniLoadingDialog.show();
                    DoScanDataModel model = new DoScanDataModel(txtTaskNo.getText().toString(), TaskDetailID, txtVehicleNo.getText().toString(), txtPanelNo.getText().toString(), OPT, userName, txtCarNo.getText().toString().trim());
                    RequestModel requestModel = new RequestModel();
                    requestModel.setJson(JsonUtil.toJson(model));
                    String json = JsonUtil.toJson(requestModel);
                    System.out.println(json);
                    XHttp.post("api/WHSmartWhousePDA/ScanDataSubmitForSMT")
                            .upJson(JsonUtil.toJson(requestModel))
                            .syncRequest(false)
                            .onMainThread(true)
                            .timeOut(150000)
                            .execute(new SimpleCallBack<ScanVehPlateModel>() {
                                @Override
                                public void onSuccess(ScanVehPlateModel response) {

                                    mMiniLoadingDialog.dismiss();
                                    ScanVehPlate = response;

                                    if (StringUtils.equals("", response.getPlateNumber())) {
                                        MediaPlayer mp = MediaPlayer.create(SMTMaterialOutStockTaskDetailActivity.this, R.raw.error_voice);
                                        mp.start();
                                        new MaterialDialog.Builder(SMTMaterialOutStockTaskDetailActivity.this)
                                                .iconRes(R.drawable.icon_warning)
                                                .title(R.string.tip_warning)
                                                .content("归还列表为空！")
                                                .positiveText(R.string.lab_submit)
                                                .show();
                                        return;
                                    }
                                    Boolean flag = false;

                                    scanQty = scanQty + Double.parseDouble(response.getQTY());

                                    txtRemovedQty.setText(String.valueOf(scanQty));
                                    for (MaterialDetailForSMTModel detail : MaterialDetails) {
                                        if (StringUtils.equals(ScanVehPlate.getVehicleNumber(), detail.getVehicleNumber())) {
                                            flag = true;
                                            detail.setFlag("2");
                                            int scannum = Integer.parseInt(detail.getScannum()) + 1;
                                            detail.setScannum(String.valueOf(scannum));
                                            if (StringUtils.equals(detail.getScannum(), detail.getPlateCount())) {
                                                detail.setFlag("2");
                                            } else {
                                                detail.setFlag("1");
                                            }
                                            break;
                                        }
                                        if (StringUtils.equals(ScanVehPlate.getPlateNumber(), detail.getVehicleNumber())) {
                                            flag = true;
                                            detail.setFlag("2");
                                            int scannum = Integer.parseInt(detail.getScannum()) + 1;
                                            detail.setScannum(String.valueOf(scannum));
                                            if (StringUtils.equals(detail.getScannum(), detail.getPlateCount())) {
                                                detail.setFlag("2");
                                            } else {
                                                detail.setFlag("1");
                                            }
                                            break;
                                        }
//                                        detail.setFlag("1");//未下完黄色
//                                        int qty=(int)Math.round(Double.parseDouble(txtRemovedQty.getText().toString()));
//                                        if(StringUtils.equals(String.valueOf(qty), txtUnremovedQty.getText().toString()))
//                                        {
//                                            detail.setFlag("2");//都下完是绿色
//                                        }
                                    }
                                    if (!flag) {
                                        new MaterialDialog.Builder(SMTMaterialOutStockTaskDetailActivity.this)
                                                .iconRes(R.drawable.icon_warning)
                                                .title(R.string.tip_warning)
                                                .content("载具号/盘号不在列表中")
                                                .positiveText(R.string.lab_submit)
                                                .show();
                                        txtVehicleNo.setText("");
                                        txtVehicleNo.requestFocus();
                                        return;
                                    }
                                    txtVehicleNo.setText("");
                                    txtVehicleNo.requestFocus();
                                    txtPanelNo.setText("");
                                    SMTMaterialOutStockTaskDetailAdapter MaterialOutStockTaskDetailsAdapter = new SMTMaterialOutStockTaskDetailAdapter(SMTMaterialOutStockTaskDetailActivity.this, MaterialDetails);
                                    txtList.setAdapter(MaterialOutStockTaskDetailsAdapter);


                                }

                                @Override
                                public void onError(ApiException e) {
                                    mMiniLoadingDialog.dismiss();
                                    txtVehicleNo.setText("");
                                    txtVehicleNo.requestFocus();
                                    MediaPlayer mp = MediaPlayer.create(SMTMaterialOutStockTaskDetailActivity.this, R.raw.error_voice);
                                    mp.start();
                                    new MaterialDialog.Builder(view.getContext())
                                            .iconRes(R.drawable.icon_warning)
                                            .title(R.string.tip_warning)
                                            .content(e.getMessage())
                                            .positiveText(R.string.lab_submit)
                                            .show();
                                }
                            });
                }
                return false;
            }
        });
        txtCarNo.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent event) {

                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    if (StringUtils.equals("", txtCarNo.getText().toString())) {
                        mMiniLoadingDialog.dismiss();
                        MediaPlayer mp = MediaPlayer.create(SMTMaterialOutStockTaskDetailActivity.this, R.raw.error_voice);
                        mp.start();
                        XToastUtils.success("请先扫描车号", 1500);
                        txtCarNo.requestFocus();
                        return false;
                    }

                    XHttp.get("api/WHSmartWhousePDA/CheckCarNoForSMT")
                            .params("CarNo", txtCarNo.getText().toString())
                            .syncRequest(false)
                            .onMainThread(true)
                            .timeOut(120000)
                            .execute(new SimpleCallBack<Boolean>() {
                                @Override
                                public void onSuccess(Boolean response) {
                                    txtVehicleNo.requestFocus();
                                }

                                @Override
                                public void onError(ApiException e) {
                                    mMiniLoadingDialog.dismiss();
                                    txtCarNo.setText("");
                                    txtCarNo.requestFocus();
                                    MediaPlayer mp = MediaPlayer.create(SMTMaterialOutStockTaskDetailActivity.this, R.raw.error_voice);
                                    mp.start();
                                    new MaterialDialog.Builder(view.getContext())
                                            .iconRes(R.drawable.icon_warning)
                                            .title(R.string.tip_warning)
                                            .content(e.getMessage())
                                            .positiveText(R.string.lab_submit)
                                            .show();
                                }
                            });
                }
                return false;
            }
        });

        txtVehicleNo.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent event) {
//                mMiniLoadingDialog.show();
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    if (StringUtils.equals("", txtVehicleNo.getText().toString())) {
                        mMiniLoadingDialog.dismiss();
                        MediaPlayer mp = MediaPlayer.create(SMTMaterialOutStockTaskDetailActivity.this, R.raw.error_voice);
                        mp.start();
                        XToastUtils.success("请先扫描载具号/盘号", 1500);
                        txtVehicleNo.requestFocus();
                        return false;
                    }
                    Boolean fg = false;
                    for (MaterialDetailForSMTModel detail : MaterialDetails) {
                        if (StringUtils.equals(txtVehicleNo.getText().toString(), detail.getVehicleNumber())) {
                            fg = true;
                            String Status = detail.getVehicleStatus().toString();
                            if (StringUtils.equals("部分", Status)) {
                                return true;
                            }
                            break;
                        }
                    }
                    if (!fg) {
                        new MaterialDialog.Builder(SMTMaterialOutStockTaskDetailActivity.this)
                                .iconRes(R.drawable.icon_warning)
                                .title(R.string.tip_warning)
                                .content("载具号/盘号不在列表中")
                                .positiveText(R.string.lab_submit)
                                .show();
                        txtVehicleNo.setText("");
                        txtVehicleNo.requestFocus();
                        return false;
                    }


//                    mMiniLoadingDialog.show();
                    DoScanDataModel model = new DoScanDataModel(txtTaskNo.getText().toString(), TaskDetailID, txtVehicleNo.getText().toString(), txtPanelNo.getText().toString(), OPT, userName, txtCarNo.getText().toString().trim());
                    RequestModel requestModel = new RequestModel();
                    requestModel.setJson(JsonUtil.toJson(model));
                    String json = JsonUtil.toJson(requestModel);
                    System.out.println(json);
                    XHttp.post("api/WHSmartWhousePDA/ScanDataSubmitForSMT")
                            .upJson(JsonUtil.toJson(requestModel))
                            .syncRequest(false)
                            .onMainThread(true)
                            .timeOut(120000)
                            .execute(new SimpleCallBack<ScanVehPlateModel>() {
                                @Override
                                public void onSuccess(ScanVehPlateModel response) {

                                    mMiniLoadingDialog.dismiss();
                                    ScanVehPlate = response;
                                    if (StringUtils.equals("", response.getVehicleNumber())) {
                                        MediaPlayer mp = MediaPlayer.create(SMTMaterialOutStockTaskDetailActivity.this, R.raw.error_voice);
                                        mp.start();
                                        new MaterialDialog.Builder(SMTMaterialOutStockTaskDetailActivity.this)
                                                .iconRes(R.drawable.icon_warning)
                                                .title(R.string.tip_warning)
                                                .content("归还列表为空！")
                                                .positiveText(R.string.lab_submit)
                                                .show();
                                        return;
                                    }

                                    Boolean flag = false;
                                    scanQty = scanQty + Double.parseDouble(response.getQTY());

                                    txtRemovedQty.setText(String.valueOf(scanQty));
                                    for (MaterialDetailForSMTModel detail : MaterialDetails) {
                                        if (StringUtils.equals(ScanVehPlate.getVehicleNumber(), detail.getVehicleNumber())) {
                                            flag = true;
                                            detail.setFlag("2");
                                            int scannum = Integer.parseInt(detail.getScannum()) + Integer.parseInt(detail.getPlateCount());
                                            detail.setScannum(String.valueOf(scannum));
                                            if (StringUtils.equals(detail.getScannum(), detail.getPlateCount())) {
                                                detail.setFlag("2");
                                            } else {
                                                detail.setFlag("1");
                                            }
                                            break;
                                        }
//                                        if (StringUtils.equals(ScanVehPlate.getPlateNumber(), detail.getVehicleNumber())) {
//                                            flag = true;
//                                            detail.setFlag("2");
//                                            int scannum=Integer.parseInt(detail.getScannum())+1;
//                                            detail.setScannum(String.valueOf(scannum));
//                                            break;
//                                        }
//                                        detail.setFlag("1");//未下完黄色
//                                        int qty=(int)Math.round(Double.parseDouble(txtRemovedQty.getText().toString()));
//                                        if(StringUtils.equals(String.valueOf(qty), txtUnremovedQty.getText().toString()))
//                                        {
//                                            detail.setFlag("2");//都下完是绿色
//                                        }
                                    }
                                    if (!flag) {
                                        new MaterialDialog.Builder(SMTMaterialOutStockTaskDetailActivity.this)
                                                .iconRes(R.drawable.icon_warning)
                                                .title(R.string.tip_warning)
                                                .content("载具号/盘号不在列表中")
                                                .positiveText(R.string.lab_submit)
                                                .show();
                                        txtVehicleNo.setText("");
                                        txtVehicleNo.requestFocus();
                                        return;
                                    }
                                    txtVehicleNo.setText("");
                                    txtVehicleNo.requestFocus();

                                    SMTMaterialOutStockTaskDetailAdapter MaterialOutStockTaskDetailsAdapter = new SMTMaterialOutStockTaskDetailAdapter(SMTMaterialOutStockTaskDetailActivity.this, MaterialDetails);
                                    txtList.setAdapter(MaterialOutStockTaskDetailsAdapter);


                                }

                                @Override
                                public void onError(ApiException e) {
                                    mMiniLoadingDialog.dismiss();
                                    txtVehicleNo.setText("");
                                    txtVehicleNo.requestFocus();
                                    MediaPlayer mp = MediaPlayer.create(SMTMaterialOutStockTaskDetailActivity.this, R.raw.error_voice);
                                    mp.start();
                                    new MaterialDialog.Builder(view.getContext())
                                            .iconRes(R.drawable.icon_warning)
                                            .title(R.string.tip_warning)
                                            .content(e.getMessage())
                                            .positiveText(R.string.lab_submit)
                                            .show();
                                }
                            });
                }
                return false;
            }
        });

    }

    @Override
    public void onClick(View view) {

    }

    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        return false;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

    }
}



